package com.cqndt.disaster.device.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;

/**
 * Created By marc
 * Date: 2018/12/24  14:32
 * Description:图片、视频、文件预览
 */
public class FileView {
    private static Logger logger = LoggerFactory.getLogger(FileView.class);

    /**
     *  预览
     * @param attachmentUrl 数据库保存路径
     * @param response
     * @param operateType 下载：1 预览：0
     * @throws Exception
     */
    public static void readByIo(String attachmentType,String attachmentUrl,HttpServletResponse response, Integer operateType,
                                String attachmentUrlSet,String openOfficePath,String openOfficeHost)throws Exception{
        StringBuffer filePath = new StringBuffer(attachmentUrlSet+File.separator);
        String destFile = attachmentUrlSet+File.separator;
        if("2".equals(attachmentType)){
            filePath.append("video");
            destFile = destFile+"video";
        }else if("3".equals(attachmentType)){
            filePath.append("file");
            destFile = destFile+"file";
        }else{
            filePath.append("img");
            destFile = destFile+"img";
        }
        filePath.append(File.separator+attachmentUrl);
        // 获取文件的后缀名
        String suffixName = attachmentUrl.substring(attachmentUrl.lastIndexOf("."));
        if(operateType == 0){
            if(suffixName.equalsIgnoreCase(".jpg")||suffixName.equalsIgnoreCase(".png")
                    ||suffixName.equalsIgnoreCase(".gif")||suffixName.equalsIgnoreCase(".tif")
                    ||suffixName.equalsIgnoreCase(".jpeg")||suffixName.equalsIgnoreCase(".svg")
                    ||suffixName.equalsIgnoreCase(".bmp")||suffixName.equalsIgnoreCase(".webp")){
                readImgByIO(filePath.toString(),response,"image/*;charset=utf-8");
            }else if(suffixName.equalsIgnoreCase(".doc")||suffixName.equalsIgnoreCase(".docx")
                    ||suffixName.equalsIgnoreCase(".xls")||suffixName.equalsIgnoreCase(".xlsx")
                    ||suffixName.equalsIgnoreCase(".ppt")||suffixName.equalsIgnoreCase(".pptx")){
                int begin=attachmentUrl.lastIndexOf(".");
                destFile = destFile+File.separator+attachmentUrl.substring(0,begin)+".pdf";
                int i = FileConverter.office2PDF(filePath.toString(),destFile,openOfficePath,openOfficeHost);
                if(i == 0){
                    readImgByIO(destFile,response,"application/pdf;charset=utf-8");
                }else{
                    logger.error("转换异常");
                    throw new Exception("转换异常");
                }
            }else if(suffixName.equalsIgnoreCase(".pdf")){
                readImgByIO(filePath.toString(),response,"application/pdf;charset=utf-8");
            }else if(suffixName.equalsIgnoreCase(".txt")){
                readImgByIO(filePath.toString(),response,"text/plain;charset=utf-8");
            }else if(suffixName.equalsIgnoreCase(".mp4")||suffixName.equalsIgnoreCase(".avi")
                    ||suffixName.equalsIgnoreCase(".rmvb")||suffixName.equalsIgnoreCase(".mkv")
                    ||suffixName.equalsIgnoreCase(".ogg")
                    ||suffixName.equalsIgnoreCase(".flv")
                    ||suffixName.equalsIgnoreCase(".wmv")){
                readImgByIO(filePath.toString(),response,"video/mpeg4;charset=utf-8");
            }else{
                throw new Exception("此文件不可预览");
            }
        }else{
            downLoad(filePath.toString(),response,false);
        }
    }

    public HttpServletResponse download(String path, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;
    }

    /**
     * 文件下载(支持在线打开)
     */
    public static void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {
        File f = new File(filePath);
        if (!f.exists()) {
            response.sendError(404, "文件不存在");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;
        response.reset();
        if (isOnLine) { // 在线打开方式
            URL u = new URL("file:///" + filePath);
            response.setContentType(u.openConnection().getContentType());
            response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
            // 文件名应该编码成UTF-8
        } else { // 纯下载方式
            //response.setContentType("application/x-msdownload");
            response.setContentType("application/octet-stream");
          //  response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
        }
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        br.close();
        out.close();
    }
    /**
     * 流的形式输出
     */
    private static void readImgByIO(String filePath,HttpServletResponse response,String contentType) throws IOException {
        File filePic = new File(filePath);
        if(filePic.exists()){
            ServletOutputStream out = null;
            FileInputStream ips = null;
            try{
                ips = new FileInputStream(filePic);
                int i = ips.available(); // 得到文件大小
                byte data[] = new byte[i];
                ips.read(data); // 读数据
                response.setContentType(contentType); // 设置返回的文件类型
                out = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
                out.write(data); // 输出数据
                out.flush();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                out.close();
                ips.close();
            }
        }
    }
}
